<template>
  <div class="message">
    <div id="messageContainer" class="content">
      <!-- <div class="scroll"> -->        
      <pull-to :top-load-method="refresh" class="scroll" :top-config="topConfig" id="messageScroll">
        <ul class="list">
          <div v-for="(item, index) in messageList" :key="index">
            <li class="showTxt left">
              {{ item.content }}
              <div class="student leftName">
                {{ item.nickName }}
              </div>
            </li>
            <div style="clear:both"></div>
          </div>

          <!-- <li class="showTxt left">
            hello!!
            <div class="student leftName">孙大炮</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt right">
            Hi!!<br />Hi!!
            <div class="student rightName">林美丽</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            打卡 打卡 打卡
            <div class="student leftName">没有名字</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            Hi!!<br />Hi!!
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            Hi!!<br />Hi!!
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            hello!!
            <div class="student leftName">孙大炮</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt right">
            Hi!!<br />Hi!!
            <div class="student rightName">林美丽</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            打卡 打卡 打卡
            <div class="student leftName">没有名字</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            Hi!!<br />Hi!!
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            Hi!!<br />Hi!!
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div>
          <li class="showTxt left">
            test
            <div class="student leftName">test</div>
          </li>
          <div style="clear:both"></div> -->
        </ul>
      </pull-to>
      <!-- </div> -->
    </div>
  </div>
</template>

<script>
import { initWebSocket, close } from "../utils/websocket";
import { MessageKey, EventManager, enterRoom } from "../api/message";
import { courseMesssageNonList } from "../api/course";
import PullTo from 'vue-pull-to'

var ActionType = {
  NewMessage: 1,
  End: 2
};

export default {
  components: {
    PullTo
  },
  data() {
    return {
      courseId: "",
      params: {},
      messageList: [],
      messageLength: 200,
      topConfig: {
        pullText: '下拉加载更多', // 下拉时显示的文字
        triggerText: '释放开始加载', // 下拉到触发距离时显示的文字
        loadingText: '加载中...', // 加载中的文字
        doneText: '加载完成', // 加载完成的文字
        failText: '加载失败', // 加载失败的文字
        loadedStayTime: 500, // 加载完后停留的时间ms
        stayDistance: 30, // 触发刷新后停留的距离
        triggerDistance: 40 // 下拉刷新触发的距离
      }
    };
  },
  created() {
    localStorage.clear();
    close();
  },
  mounted() {
    console.log(this.$route.query.token);
    console.log(this.$route.query.server);
    console.log(this.$route.query.userId);

    this.registerEvent();

    this.params = {
      userId: this.$route.query.userId,
      userName: "",
      token: this.$route.query.token,
      host: this.$route.query.server,
      visitor: 1,
      apiTime: this.$route.query.apiTime
    };
    this.courseId = this.$route.query.liveCourseId;
    console.log(this.params)
    const userJson = JSON.stringify(this.params)
    localStorage.setItem("currentUser", userJson);
    localStorage.setItem("ws", this.params.host);
    this.loadCourseMessage();
  },
  beforeDestroy() {},
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        let msg = document.getElementsByClassName("scroll-container")[0]; // 获取对象
        if (msg && msg.scrollHeight) {
          msg.scrollTop = msg.scrollHeight; // 滚动高度
        }
      });
    },
    refresh(loaded) {
      this.loadCourseMessage(loaded);
    },
    loadCourseMessage(loaded = null) {
      var lastMsgId = 0;
      if (this.messageList && this.messageList.length > 0) {
        if (this.messageList[0].id) {
          lastMsgId = this.messageList[0].id;
        }
      }

      courseMesssageNonList(
        this.params.token,
        this.params.userId,
        this.courseId,
        this.params.apiTime,
        lastMsgId
      )
        .then(response => {
          if (response && response.data && response.data.length > 0) {
            if (this.messageList && this.messageList.length > 0) {
              this.messageList = response.data.concat(this.messageList);
            } else {
              this.messageList = response.data;
            }
          }

          if (loaded) {
            loaded('done')
          }

          // var t;
          // clearTimeout(t);
          // t = setTimeout(() => {
          //   this.scrollToBottom();
          // }, 500);

          initWebSocket();
        })
        .catch(error => {
          console.log(error);
          this.$toastErrorCode(error);
        });
    },
    loginSuccess() {
      enterRoom(this.courseId);
    },
    receivedMessage(data) {
      if (
        data &&
        data.liveCourseMsg &&
        data.liveCourseMsg.liveCourseId &&
        data.liveCourseMsg.liveCourseId == this.courseId
      ) {
        var message = {};
        message.userId = data.userId;
        message.nickName = data.liveCourseMsg.nickName;
        message.content = data.liveCourseMsg.content;
        this.messageList.push(message);

        // if (this.messageList.length > this.messageLength) {
        //   this.messageList.shift();
        // }

        // 滚动
        this.scrollToBottom();

        this.callWindow(ActionType.NewMessage);
      }
    },
    receivedCourseState(data) {
      if (
        data &&
        data.liveCoursePlayState.liveCourseId == this.courseId &&
        data.liveCoursePlayState.playState == "END"
      ) {
        this.callWindow(ActionType.End);
      }
    },
    callWindow(type) {
      // window.open("obsmsg://action?type=" + type);
      // window.location.href = "obsmsg://action?type=" + type;
      if (!self.obs) return;

      switch (type) {
        case ActionType.NewMessage:
          self.obs.notifyAction("message", "{}");
          break;
        case ActionType.End:
          self.obs.notifyAction("close", "{}");
          break;
      }
    },
    registerEvent() {
      EventManager.Register(
        MessageKey.login,
        this.loginSuccess.bind(this),
        this
      );
      EventManager.Register(
        MessageKey.liveCourseMsg,
        this.receivedMessage.bind(this),
        this
      );
      EventManager.Register(
        MessageKey.liveCoursePlayState,
        this.receivedCourseState.bind(this),
        this
      );
      this.$once("hook:beforeDestroy", () => {
        EventManager.UnRegister(MessageKey.login, this);
        EventManager.UnRegister(MessageKey.liveCourseMsg, this);
        EventManager.UnRegister(MessageKey.receivedCourseState, this);
      });
    }
  }
};
</script>

<style lang="stylus" scoped>
.message {
  margin: 0 auto;
  position: absolute;
  top: 0px;
  bottom: 0px;
  width: 100%;
  font-size: 14px;
}

.message .content {
  height: calc(100% - 10px);
  overflow-y: auto;
}

.message .content .scroll {
  position: relative;
}

.message .content .scroll ul {
  margin: 0;
  padding: 0;
}

.message .edit {
  background: #ece7e766;
  height: 40px;
}

.message .txt {
  margin-top: 3px;
  margin-left: 3px;
  position: absolute;
  border-radius: 2px;
  border:1px solid #ccc;
  height: 30px;
  width: calc(100% - 88px);
  border-radius: 0;
  box-shadow: none;
  border-color: #d2d6de;
  font-size: 14px;
  line-height: 14px;
  padding: 0 5px;
}

.message .btn {
  margin-top: 3px;
  right: 3px;
  position: absolute;
  background-color: #00c0ef;
  border-color: #00acd6;
  padding: 6px 20px;
  font-size: 14px;
  line-height: 1.42857143;
  color : #fff;
}

.message .showTxt {
  width: auto;
  height: auto;
  max-width: 290px;
  background: #d2d6de;
  border: 0;
  font-size: 15px;
  color: #444;
  padding: 5px 10px;
  border-radius: 2px;
  word-break: break-all;
  list-style: none;
  margin-top: 30px;
  display: list-item;
  position: relative;
}

.message .left {
  text-align: left;
  margin-left: 20px;
  float: left;
}

.message .right {
  text-align: left;
  margin-right: 20px;
  float: right;
  background: #f39c12;
  color: #fff;
}

.message .student {
  color: #999;
  text-overflow: clip;
  font-size: 12px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  line-height: 16px;
  top: -18px;
}

.message .leftName {
  left: -0.5px;
  position: absolute;
}

.message .rightName {
  right: -0.5px;
  position: absolute;
}
</style>
